package fr.efrei.tradesys.hibernate.daoImpl;

import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.Session;
import org.hibernate.criterion.Restrictions;

import fr.efrei.tradesys.hibernate.HibernateUtil;
import fr.efrei.tradesys.hibernate.beans.AppUser;
import fr.efrei.tradesys.hibernate.dao.AppUserDao;

public class AppUserDaoImpl implements AppUserDao
{

	private static AppUserDaoImpl	instance	= new AppUserDaoImpl();

	public static AppUserDaoImpl getInstance()
	{
		return instance;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<AppUser> getAllAppUser()
	{
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Criteria criteria = session.createCriteria(AppUser.class);
		List<AppUser> list = (List<AppUser>) criteria.list();
		return list;
	}

	@SuppressWarnings("unchecked")
	public List<AppUser> getAllEnabledAppUser()
	{
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Criteria criteria = session.createCriteria(AppUser.class).add(
				Restrictions.eq("enabled", true));
		List<AppUser> list = (List<AppUser>) criteria.list();
		return list;
	}

	@SuppressWarnings("unchecked")
	@Override
	public AppUser getAppUser(String login)
	{
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		Criteria criteria = session.createCriteria(AppUser.class).add(
				Restrictions.eq("login", login));
		List<AppUser> list = (List<AppUser>) criteria.list();
		if (list.size() > 0)
			return list.get(0);
		return null;
	}

	@Override
	public void addAppUser(AppUser u)
	{
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.saveOrUpdate(u);
	}

	@Override
	public void updateAppUser(AppUser u)
	{
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.saveOrUpdate(u);
	}

	@Override
	public void removeAppUser(AppUser u)
	{
		Session session = HibernateUtil.getSessionFactory().getCurrentSession();
		session.delete(u);
	}

}
